package com.atguigu.gmall.manage;

import org.csource.common.MyException;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

public class PmsUploadUtil {
    public static String uploadImage(MultipartFile multipartFile) {
        String imgUrl = "http://192.168.141.103";
        //上传图片到服务器
        //配置fdfs的全局连接地址
        String tracker = PmsUploadUtil.class.getResource("/tracker.conf").getPath();//配置文件路径
        try {
            ClientGlobal.init(tracker);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }
        TrackerClient trackerClient = new TrackerClient();
        //获得一个TrackerServer的实例
        TrackerServer trackerServer = null;
        try {
            trackerServer = trackerClient.getConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }
        StorageClient storageClient =  new StorageClient(trackerServer,null);
        try{
            byte[] bytes = multipartFile.getBytes();//获取上传的二进制对象
            String originalFilename = multipartFile.getOriginalFilename();//获取文件名字
            System.out.println(originalFilename);
            int i = originalFilename.lastIndexOf(".");
            String extName = originalFilename.substring(i+1);
            String[] uploadInfos = storageClient.upload_file(bytes, extName, null);
            for(String uploadInfo : uploadInfos){
                imgUrl += "/" + uploadInfo;
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return imgUrl;
    }
}
